| Oracle® Enterprise Manager Command Line Interface 12c Release 1 (12.1.0.3) Part Number E17786-08 |
|
|
PDF · Mobi · ePub |
This chapter discusses the following Enterprise Manager Command Line Interface (EM CLI) topics:
Command-line EM CLI is the traditional and most direct way of invoking an EM CLI verb. The basic syntax from the system prompt is:
emcli verb_name -required_parameter1 -required_parameter2 ... -option1 -option2 ...
The syntax for a particular verb applies to its usage whether it is invoked through the command line or programatically. For example, the syntax for the create_group verb is:
emcli create_group
-name="name"
[-type=<group>]
[-add_targets="name1:type1;name2:type2;..."]...
[-is_propagating="true/false"]
This indicates that -name is required, whereas -type, enclosed within brackets, is optional, as well as -add_targets and -is_propagating. The following example shows how the verb might be used at the command-line prompt:
emcli create_group -name=db_group
-add_targets="emp_rec:oracle_database"
-add_targets="payroll:oracle_database"
Chapter 4, "Verb Reference" provides the format, descriptions of required and optional parameters, and examples for most EM CLI verbs. Those that are not documented can be found in the online help by typing emcli help verb_name.
As introduced in Chapter 1, EM CLI provides programmatic methods in the form of Interactive and Script modes to enhance and extend the basic functionality offered through the standard command-line invocation.
The following sections discuss the fundamental principles associated with the programatic usage of EM CLI:
Beginning with Enterprise Manager Cloud Control version 12cR3, EM CLI includes an embedded Jython interpreter (Jython 2.5.1), where all of the verbs are registered as functions, known as EM CLI verb functions or simply functions. Usage of these functions is similar to the corresponding verb. In these functions, the parameters (supplied as key-value pairs) are those present in the verb arguments.
The following examples contrast standard verb invocations and Interactive mode invocations.
Example 1 — String-based Arguments
Standard invocation:
% emcli create_user -name='jan.doe' -type='EXTERNAL_USER'
Interactive mode invocation:
emcli>create_user(name='jan.doe',type='EXTERNAL_USER')
Example 2 — List-based Arguments
Standard invocation:
% emcli grant_privs -name='jan.doe' \
-privilege="USE_ANY_BEACON" \
-privilege="FULL_TARGET;TARGET_NAME=host1.example.com:TARGET_TYPE=host"
Interactive mode invocation:
emcli>priv_list = ['USE_ANY_BEACON','FULL_TARGET;TARGET_NAME=host1.example.com: TARGET_TYPE=host'] emcli>grant_privs(name='jan.doe',privilege=priv_list)
Example 3 — Flag-based Boolean Arguments
Standard invocation:
% emcli get_targets -noheader
Interactive mode invocation:
emcli>get_targets(noheader=True)
EM CLI provides two modes to run a Jython program: Script mode and Interactive mode. Using Script mode, you can run your Jython program by passing it to the interpreter in a non-interactive fashion. To run a script, type emcli and provide the script location as shown in the following example, in which my_script.py is the full path of a valid Python script:
%emcli @my_script.py
In Interactive mode, the interpreter opens a shell where you can type your commands. To start EM CLI in Interactive mode, type emcli at the command prompt as shown in the following example:
% emcli
For both modes, apart from using the EM CLI verb functions, you can also program in Jython conventionally.
Both Script and Interactive mode provide the same functionality. Unless otherwise stated explicitly, all of the information presented in this chapter pertains to both Script and Interactive modes.
To illustrate using the interpreter in both Interactive and Script mode to achieve the same objective, the following examples print the current version of the installed EM CLI client. Example 3-1 shows a Python script that uses the version() verb of EM CLI to print the current version. Example 3-2 achieves the same result using the interactive shell. Note that the version verb used in both of these examples has the same signature and functionality.
To assist you in writing your first script, this section analyzes a sample script that retrieves all targets and prints their names. Example 3-3 shows the entire script.
Note:
Line numbers are provided only for illustrative purposes.Example 3-3 Script That Retrieves All Targets and Prints Their Names
1 #emcli_get_targets.py
2
3 #Import all emcli verbs to current program
4 from emcli import *
5
6 def print_target_details(target):
7 '''
8 print the target name and target type given a target tuple.
9 '''
10 print target['Target Name'] + ' ' + target['Target Type']
11
12 #Set the OMS URL to connect to
13 set_client_property('EMCLI_OMS_URL','https://host1.example.com:1234/em')
14 #Accept all the certificates
15 set_client_property('EMCLI_TRUSTALL','true')
16
17 #Login to the OMS
18 login(username='adminuser')
19
20 #Invoke get_targets and loop over the targets array
21 targets_array = get_targets().out()['data']
22 for target in targets_array:
23 #Call print_target_details function to print the target details
24 print_target_details(target)
Note:
Observe the method of accessing the JSON response from the verb response get_targets().out()['data']. The get_targets() response provides a handle to the response object, and out()['data'] provides a handle over the underlying JSON data. This methodology is consistent for all verbs.Table 3-1 provides an analysis of each line of code.
Table 3-1 Line-by-Line Script Analysis
| Lines | Description |
|---|---|
|
4 |
Jython import construct to import all EM CLI verb functions in the current program. You can also selectively import the verb functions. You can use the Jython import function to import all of the functions as wildcards or on an as needed basis explicitly. For example: from emcli import * ... imports all of the functions, whereas ... from emcli import get_targets ... imports only the get_targets function. |
|
6 - 10 |
Custom Jython function to print the name and type of a target. It accepts a key value tuple of the form. It accepts a key value tuple of the form {Target Name, Target Type} as the parameters. |
|
13, 15 |
Necessary connection to OMS in order to get all targets. Before connecting to the OMS, you must first set the OMS connection details using the set_client_property() function. This sets the OMS URL to https://host1.example.com:1234/em and enables the client to trust all certificates. Note that none of these details are stored in disk. These details are stored in memory and only last for a single script execution. For more information on client properties, enter help('client_properties') from the interactive shell. You can define EMCLI_OMS_URL and EMCLI_TRUSTALL variables as environment variables if you do not want to set these in your script. If you have downloaded certificates somewhere, you can also use the environment variable EMCLI_CERT_LOC to point to the certificate directory. In this case, you do not need EMCLI_TRUSTALL. |
|
18 |
Login function to connect to the OMS. The example uses the sysman user to log in. This prompts for a password during execution. |
|
21 - 24 |
Invokes the get_targets() function and captures its response in an array called targets_array. This is in JSON format. This example iterates through this array and uses the custom function print_target_details to print its name and type. |
Example 3-4 shows that executing this script retrieves the list of all targets and their types.
Example 3-4 Output of Script that Retrieves All Targets
$emcli @emcli_get_targets.py Enter password : ****** test.example.com host EM Management Beacon oracle_beacon CSAcollector oracle_csa_collector Oemrep_Database oracle_database EM Jobs Service oracle_em_service test.example.com:1838 oracle_emd Management Services and Repository oracle_emrep Management_Servers oracle_emsvrs_sys test.example.com:7654_Management_Service oracle_oms test.example.com:7654_Management_Service_CONSOLE oracle_oms_console test.example.com:7654_Management_Service_PBS oracle_oms_pbs /EMGC_EMGC_DOMAIN/EMGC_DOMAIN weblogic_domain Logout successful
The Logout Successful message indicates that the login session to the OMS is closed at the end of the execution.
As mentioned earlier, all of the verbs are available as global Jython functions with verb options as function parameters. Flag-based options are provided by specifying True as the value. List-based options are provided by constructing a Python list and using it as an argument. Table 3-7 provides more details on this.
Every EM CLI verb invocation returns a Response object. The Response object is part of EM CLI, and has the functions listed in Table 3-2.
Table 3-2 Response Object Functions
| Function | Description |
|---|---|
|
out() |
Provides the verb execution output. The output can be text, or the JSON.isJson() method on the Response object can be used to determine whether the output is JSON. Refer to the section "JSON Processing" for more details. |
|
error() |
Provides the error text (if any) of the verb execution if there are any errors or exceptions during verb execution. Refer to the section "Error and Exception Handling" for more details. |
|
exit_code() |
Provides the exit code of the verb execution. The exit code is zero for a successful execution and non-zero otherwise. Refer to the section "Error and Exception Handling" for more details. |
|
isJson() |
Provides details about the type of output. It returns True if response.out() can be parsed into a JSON object. |
Example 3-5 invokes the get_targets verb and prints the output, error, and exit code of the execution.
Note:
Line numbers are provided only for illustrative purposes.Example 3-5 Script that Incorporates Functions in the get_targets Verb
1 #emcli_introspect_response.py
2
3 #Import all emcli verbs to current program
4 from emcli import *
5
6 #Set the OMS URL to connect to
7 set_client_property('EMCLI_OMS_URL','https://host1.example.com:1234/em')
8 #Accept all the certificates
9 set_client_property('EMCLI_TRUSTALL','true')
10
11 #Login to the OMS
12 login(username='sysman')
13
14 res = get_targets()
15
16 print 'Number of targets:'+str(len(res.out()['data']))
17 print 'Errors :'+res.error()
18 print 'Exit code :'+str(res.exit_code())
19 print 'IsJson :'+str(res.isJson())
Line 16 shows that instead of printing the raw response (which will be JSON), the example uses the Jython len() function to print the length of the response array, which is basically the count of all of the targets. Note that the example uses the Jython str() function to convert an integer type to a string.
Example 3-6 shows the execution of the script in Example 3-5.
If a verb response is JSON, it can be programmatically iterated and accessed. You can use response.isJson() to check whether the verb output is JSON. If the verb output is JSON, response.out()['data'] provides the object in the Jython object model.
JSON processing has been shown in previous examples. Example 3-7 shows another example of this processing. The example uses custom SQL with the list() function, which provides a generic method to retrieve data about managed objects in Enterprise Manager. Custom SQL only works if the OMS user has super user privileges.
Note:
Line numbers are provided only for illustrative purposes.Example 3-7 Script that Incorporates Custom SQL with the list() Function
1 #emcli_json_processing.py
2 #Import all EM CLI verbs to current program
3 from emcli import *
4 def format(str):
5 '''
6 Given a string argument returns it back or returns 7 a blank string if it is of None type
8 '''
9 if str is None:
10 return ""
11 return str
12
13 def get_targets_with_props(p_prop_name, p_prop_val):
14 '''
15 Returns targets with given property name and its value. Uses list verb.
16 '''
17 l_sql = "select target_name, target_type, property_value " \18 "from mgmt$target_properties " \
19 "where property_name = '" + p_prop_name + "' " + " " \20 "and property_value like '" + p_prop_val + "'"
21 obj = list(sql=l_sql)
22 return obj
23 #Set the OMS URL to connect to
24 set_client_property('EMCLI_OMS_URL','https://host1.example.com:1234/em')
25 #Accept all the certificates
26 set_client_property('EMCLI_TRUSTALL','true')
27 #Log in to the OMS
28 login(username='sysman')
29 #Find all the targets that have Version property set to release 12
30 l_targets = get_targets_with_props('Version', '12%')
31 for target in l_targets.out()['data']:
32 tn = target['TARGET_NAME']
33 tt = target['TARGET_TYPE']
34 pv = target['PROPERTY_VALUE']
35 print "Name "+tn + " Type =" + tt + " value=" + pv
Table 3-1 provides an analysis of relevant lines of code. The remainder of the program is similar to Example 3-3, which was analyzed in Table 3-1.
| Lines | Description |
|---|---|
|
13 - 22 |
A custom Jython function get_targets_with_props() returns all of the targets with a given property name and value. It uses the list() function or verb to query the targets. This verb, introduced in 12cR3, provides a convenient way to search the Enterprise Manager repository for resources. One of its features is to list the resources matching a given SQL query, which is used in the example. The output of this verb is JSON, which can be accessed using out()['data']. |
|
31 - 35 |
Iterates over the JSON response and prints the target name and target type. |
Example 3-4 shows that executing this script retrieves the list of all targets and their types.
If an exception or error occurs during verb execution, an exception of type emcli.exception.VerbExecutionError is raised. emcli.exception.VerbExecutionError extends from RuntimeError and hence stops the execution. You can use standard Jython exception handling to catch this exception.
emcli.exception.VerbExecutionError has the functions listed in Table 3-4.
Table 3-4 Functions for emcli.exception.VerbExecutionError
| Function | Description |
|---|---|
|
error() |
Provides the error text of the verb execution. |
|
exit_code() |
Provides the exit code of the verb execution. |
Example 3-9 shows the usage of VerbExecutionError.
Note:
Line numbers are provided only for illustrative purposes.Example 3-9 Script that Incorporates Exception Handling
1 #emcli_error_exception_handling.py
2
3 #import all emcli verbs to current program
4 from emcli import *
5 #import the verbexecutionerror
6 from emcli.exception import VerbExecutionError
7
8 #Set the OMS URL to connect to
9 set_client_property('EMCLI_OMS_URL','https://host1.example.com:1234/em')
10 #Accept all the certificates
11 set_client_property('EMCLI_TRUSTALL','true')
12
13 #Login to the OMS
14 login(username='sysman')
15
16 #Create a group
17 res = create_group(name='Jan_Doe_Group')
18
19 print res.out()
20
21 #Try to create the same group again
22 try:
23 #This will trigger an exception as the group exist already
24 create_group(name='Jan_Doe_Group')
25 except VerbExecutionError , e:
26 print e.error()
27 print 'Exit code:'+str(e.exit_code())
Table 3-1 provides an analysis of relevant lines of code.
| Lines | Description |
|---|---|
|
4, 6 |
Imports all EM CLI verbs, and imports VerbExecutionError. |
|
9, 11 |
Necessary connection to OMS in order to get all targets. Before connecting to the OMS, you must first set the OMS connection details using the set_client_property() function. This sets the OMS URL to https://host1.example.com:1234/em and enables the client to trust all certificates. Note that none of these details are stored in disk. These details are stored in memory and only last for a single script execution. For more information on client properties, enter help('client_properties') from the interactive shell. You can define EMCLI_OMS_URL and EMCLI_TRUSTALL variables as environment variables if you do not want to set these in your script. If you have downloaded certificates somewhere, you can also use the environment variable EMCLI_CERT_LOC to point to the certificate directory. In this case, you do not need EMCLI_TRUSTALL. |
|
14 |
Login function to connect to the OMS. The example uses the sysman user to log in. This prompts for a password during execution. |
|
22 - 27 |
Exception use case to create the same group again. This produces a run-time error, which the example is handling in the try except block. |
Example 3-10 shows the output of the script shown in Example 3-9.
The functions shown in Table 3-6 are also available in the EM CLI package.
Table 3-6 Additional Functions
| Function | Description |
|---|---|
|
last_out() |
Returns the output for the last executed EM CLI command. It returns None if an EM CLI command has not been executed in the current session. |
|
last_error() |
Returns the error text (if any) for the last executed EM CLI command. It returns None if an EM CLI command has not been executed in the existing session, or all of the previous executions were successful. |
|
clear() |
Clears the current shell in Interactive mode. |
|
exit(ret_val) |
Exits from the EM CLI Interactive shell with ret_val. |
You can extend EM CLI with end-user Python libraries by doing one of the following:
Copy modules to the extension directory, as shown in the following example:
$EMCLI_INSTALL_HOME/extdir
Specify the EMCLI_PYTHONPATH environment variable where the Python modules are loaded from.
Table 3-7 shows various use cases and corresponding solution examples for standard EM CLI versus interactive invocations or scripts.
| Task/Action | Usage for Standard EM CLI | Usage for EM CLI Interpreter (interactive shell or script) |
|---|---|---|
|
Invoke a verb with string-based arguments |
% emcli create_user -name='jane.doe' -type='EXTERNAL_USER' |
create_user(name='jane.doe', type='EXTERNAL_USER') |
|
Invoke a verb with list-based arguments |
% emcli grant_privs -name='jan.doe' -privilege="USE_ANY_BEACON" \ privilege="FULL_TARGET;TARGET_NAME=host1.example.com:TARGET_TYPE=host" |
#First construct a list priv_list = ['USE_ANY_BEACON','FULL_TARGET;TARGET_NAME=host1.example.com: TARGET_TYPE=host'] #Now use the list grant_privs(name='jan.doe', privilege=priv_list) |
|
Invoke a verb with flag-based Boolean arguments |
% emcli get_targets -noheader |
get_targets(noheader=True) |
|
Using help |
help $verb_name For example, help get_targets prints the help for the get_targets verb. |
help('$verb_name')
For example, help('get_targets') prints the help for the get_targets verb. |
EM CLI provides dozens of listing verbs, such as list, get, show, and describe. Rather than selecting from all of these choices, this release of EM CLI provides a generic list verb that you can execute with various types of queries.
The generic list verb provides the following benefits:
Generates JavaScript Object Notation (JSON) for script use and standard output for command-line use
Can specify your own custom SQL to retrieve data from the repository using repository views
The following sections provide examples of using the list verb for various purposes.
The list verb supports describing the registered listable resources.
To list all registered resource groups and resources:
emcli list -help
To describe a specific resource:
emcli list -resource="<resource_name>" -help
This provides a list of all of the columns along with descriptions.
To list data:
emcli list -resource="<resource_name>"
The list verb supports search capabilities.
To search using the list verb:
emcli list -resource="<resource_name>" -search="col1 = 'val1'"
To specify multiple search conditions:
emcli list -resource="<resource_name>" -search="col1" = "val1" search="col2" = val2"